<template>
    <view class="container">
        <view class="search" ref="search">
            <u-search
                @click="show = true"
                :show-action="false"
                placeholder="搜索"
                :disabled="true"
            ></u-search>
        </view>
        <view>
                <u-popup v-model="show" mode="top" length="45%">
                    <view
                    class="text-blue padding-left-sm padding-top-sm"
                    style="font-size: 18px"
                    >
                    <u-icon name="/static/common/img/find.png" size="64"></u-icon>
                    <text class="padding-left-sm text-blue">查询条件</text>
                    </view>
                    <u-form class="form" :model="query" ref="uForm" label-position="left">
                    <!-- <u-form-item class="text-bold" label="是否完成:" prop="cinvcode" label-width="200">
                                    <js-select v-model="query.cinvcode" dict-type="sys_yes_no" placeholder="请选择是否完成"></js-select>
                                </u-form-item> -->
                    <u-form-item
                        class="text-bold"
                        label="存货编码:"
                        prop="cinvcode"
                        label-width="200"
                    >
                        <u-input
                        placeholder="请输入"
                        v-model="query.cinvcode"
                        type="text"
                        maxlength="200"
                        ></u-input>
                    </u-form-item>
                    <u-form-item
                        class="text-bold"
                        label="存货名称:"
                        prop="cinvname"
                        label-width="200"
                    >
                        <u-input
                        placeholder="请输入"
                        v-model="query.cinvname"
                        type="text"
                        maxlength="200"
                        ></u-input>
                    </u-form-item>
                    </u-form>
                    <view class="footer">
                    <u-button class="btn" type="primary" @click="submit">查询</u-button>
                    <u-button class="btn margin-top-lg" @click="reset">重置</u-button>
                    </view>
                </u-popup>
            </view>
        <view class="wrap">
            <scroll-view
            scroll-y="true"
            @scrolltolower="loadMore"
            :refresher-enabled="true"
            :scrolltolower-enabled="true"
            :refresher-triggered="triggered"
            @refresherrefresh="refresherrefresh"
            @scrolltoupper="refresherrefresh"
            class="scroll-view-class"
            :style="{ height: computedScrollViewHeight }"
            >
                <view class="cu-item shadow margin raduis" style="position: relative;" v-for="(item,index) in list" @click="selectRw(item.cinvcode)">
                    <view class="cu-form-group text-xl text-bold">
                        <view class="title flex">
                            <view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px	;">
                                {{ index + 1 }}
                            </view>
                            <view>存货编码：</view>
                        </view>
                        <view class="flex-sub">{{ item.cinvcode }}</view>
                    </view>
                    <view class="cu-form-group">
                        <view class="title">存货名称：</view>
                        <view class="flex-sub">{{ item.cinvname }}</view>
                    </view>
                    <view style="position: absolute;right: 20rpx;z-index:9999;top: 50%; transform: translateY(-50%);"  v-if="checkedIndexes.includes(index)">
                        <image src="/static/image/select.png" style="width: 30px; height: 30px"></image>
                    </view>
                    
                </view>
                <view v-if="list.length" class="loadmore" style="justify-self: flex-end">
                <u-loadmore :status="loadStatus"></u-loadmore>
                </view>
                <u-empty v-if="!list.length" style="height: 100%;"></u-empty>
            </scroll-view>
            <view class="btn-group cu-bar foot padding" ref="btn-group">
                <!-- round -->
                <button class="cu-btn  bg-confirm lg margin-left " @click="confirm">确定</button>
            
            </view>
            <custom-modal
            ref="customModal"
            v-if="showModal"
            :initial-message="modalMessage"
            @update:close="onModalClose"
            ></custom-modal>
            
        </view>
    </view>

</template>

<script>
import CustomModal from "@/pages/mes/components/CustomModal.vue";
export default {
    components: {
        CustomModal,
    },
    data() {
        return {
            loadStatus: "loadmore",
            triggered: false,
            query: {
              pageNo: 1,
              pageSize: 20,
              // orderBy: "a.create_date desc",
            },
            list : [],
            checkedIndexes: [],
            scrollViewHeight: 0,
            showModal: false,
            modalMessage: "",
            show: false,
            modid:''
        }
    },
    onLoad(e){
        console.log(e)
        this.modid = e.modid
        this.query.modid = e.modid
        this.query.pageNo = 1;
        // this.query.fp = {
        // 	lineCode:e.lineCode
        // }
        this.query['fp.lineCode'] = e.lineCode
        this.loadData();
        console.log('onLoad')
    },
    async  mounted() {
        
        this.calculateScrollViewHeight()
        
    },
    computed: {
      computedScrollViewHeight() {
        return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
      },
    },
    methods:{	
        async refresherrefresh() {
          this.triggered = true;
          this.query.pageNo = 1;
          await this.loadData();
          setTimeout(() => {
            this.triggered = false;
          }, 500);
        },
        loadMore() {
          this.loadStatus = "loading";
          setTimeout(() => {
            this.query.pageNo += 1;
            this.loadData("add");
          }, 100);
        },
        loadData(type) {
          console.log('loadData')
          this.$u.api.kst.invListData(this.query).then((res) => {
            if (res.list.length < 20 || res.list.length == 0) {
              this.loadStatus = "nomore";
            }
            var data = res.list;
            if (type == "add") {
              for (var i = 0; i < data.length; i++) {
                this.list.push(data[i]);
              }
            } else {
              this.list = data;
            }
          });
        },
        selectRw(index){
            // 如果当前index已经在checkedIndexes中，则移除，否则添加
            // 如果当前index已经在数组中，移除它；否则添加它
            const currentIndexExists = this.checkedIndexes.includes(index);
            
            // 使用Set来避免在大数组中频繁的includes检查，提高效率
            const updatedIndexes = new Set(this.checkedIndexes);
            
            if (currentIndexExists) {
                updatedIndexes.delete(index);
                console.log('取消选中', index);
            } else {
                updatedIndexes.add(index);
                console.log('选中', index);
            }
            
            // 将Set转换回Array并赋值给checkedIndexes
            this.checkedIndexes = Array.from(updatedIndexes);
        },
        async calculateScrollViewHeight() {
          try {
        // 等待头部高度计算完成
              
              // 计算btn-group 高度
              // 获取屏幕高度
              const systemInfo = uni.getSystemInfoSync();
              const screenHeight = systemInfo.windowHeight;
              const searchHeight = this.$refs['search'].$el.offsetHeight;
              const btnOffsetHeight = this.$refs['btn-group'].$el.offsetHeight
              // 计算scroll-view高度
              this.scrollViewHeight = screenHeight - ( btnOffsetHeight + searchHeight);
          } catch (error) {
            console.error('Error while calculating ScrollView height:', error);
          }
        },
        confirm(){
            console.log(this.checkedIndexes.length,'checkedIndexes====')
            if(this.checkedIndexes.length===0){
                this.showCustomModal("请选择报工任务").then((res) => {
                    
                })
            }else{
                this.showCustomModal("确认当前任务报工").then((res) => {
                    if(res){
                        // 返回上一页
                        const selectedItems = this.checkedIndexes.map(index => this.list[index]);
                        console.log(selectedItems,'selectedItems====')
                        // 使用navigateBack返回上一页，并传递参数
                        uni.navigateBack({
                            delta: 1, // 返回上一页
                            success: () => {
                                // 这里可以通过eventChannel向父页面发送事件传递数据，但注意这种方式需要上一页监听相应事件
                                uni.$emit('selectedItems', selectedItems);
                            },
                            fail: (err) => {
                                console.error('返回上一页失败', err);
                            }
                        });
                    }
                    
                })					
            }

        },
        async showCustomModal(message) {
          this.modalMessage = message;
          this.showModal = true;
          // 模拟同步等待用户操作
          return new Promise((resolve) => {
            this.onModalClose = (result) => {
              this.modalResult = result;
              this.showModal = false;
              resolve(this.modalResult);
            };
          });
        },
        onModalClose(result) {
          this.$emit("update:close", result);
        },
        submit() {
            setTimeout(() => {
                this.query.pageNo = 1;
                this.loadData();
            }, 100);
            this.show = false
        },
        reset() {
            this.query = {
                    pageNo: 1,
                    pageSize: 20,
                    modid : this.modid
            };
            this.loadData();
        },
    }
}	
</script>

<style scoped>
.title{
    width: 280rpx;
}
.bg-confirm {
  background: #3e97b0;
  color: #ffffff;
}
</style>